import {Ref, useEffect, useRef} from "react";
import * as echarts from "echarts";
import {ECharts} from "echarts";
import {ECBasicOption} from "echarts/types/dist/shared";

interface Props {
    name?: string,
    width: number | string;
    height: number | string;
    options: ECBasicOption;
}

const App = ({width, height, options}: Props) => {
    const main: Ref<HTMLDivElement> = useRef(null);
    let chart: ECharts | null = null;

    useEffect(() => {
        if (!main.current) return;

        // eslint-disable-next-line react-hooks/exhaustive-deps
        chart = echarts.init(main.current);
        chart.setOption(options);

        const handleResize = () => {
            chart?.resize();
        };

        window.addEventListener("resize", handleResize);

        return () => {
            window.removeEventListener("resize", handleResize);
            chart?.dispose();
        };
    }, [options]);

    return <div ref={main} style={{width, height}}/>;
};

export default App;